import React from "react";

export function useContinued(rateTime: number): {
  (): number;
  resetTime: () => void;
};
export function useContinued(
  rateTime: number,
  overTime: number
): {
  (): boolean;
  resetTime: () => void;
};

/**
 *
 * @param rateTime 判断频率(毫秒)
 * @param overTime (可选)是否超过overTime时间
 * @returns 触发时间(Number) | 是否超过时间(Boolean)
 */
export function useContinued(rateTime = 200, overTime?: number) {
  const timeoutRef = React.useRef<number | null>(null);
  const lastExecTimeRef = React.useRef<number>();

  React.useEffect(() => {
    return () => {
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }
    };
  }, []);

  // 重置触发时长
  const resetTime = () => {
    lastExecTimeRef.current = undefined;
  };

  const continued = () => {
    if (lastExecTimeRef.current === undefined) {
      lastExecTimeRef.current = Date.now();
    }
    clearTimeout(timeoutRef.current!);
    timeoutRef.current = setTimeout(() => {
      lastExecTimeRef.current = undefined;
    }, rateTime);
    const currentTime = Date.now();
    const remainingTime = currentTime - lastExecTimeRef.current!;
    if (typeof overTime === "undefined") {
      return remainingTime;
    } else {
      return remainingTime >= overTime;
    }
  };
  continued.resetTime = resetTime;

  return continued as
    | {
        (): number;
        resetTime: () => void;
      }
    | {
        (): boolean;
        resetTime: () => void;
      };
}
